package logic

import (
	"context"
	"errors"
	"fresh-go/freshrpc/freshrpc"
	"fresh-go/freshrpc/internal/svc"
	"fresh-go/model/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type FreshAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshAddLogic {
	return &FreshAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 生鲜创建方法
func (l *FreshAddLogic) FreshAdd(in *freshrpc.FreshAddRequest) (*freshrpc.FreshAddResponse, error) {
	// todo: add your logic here and delete this line

	var fresh mysql.Fresh

	err := fresh.FreshShowByName(mysql.DB, in.FreshName)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if fresh.FreshName == in.FreshName {
		return nil, errors.New("该生鲜已存在")
	}

	fresh = mysql.Fresh{
		FreshName:  in.FreshName,
		FreshPrice: in.FreshPrice,
		FreshNum:   int(in.FreshNum),
		FreshTypes: in.FreshTypes,
	}

	err = fresh.FreshAdd(mysql.DB)
	if err != nil {
		return nil, errors.New("创建失败")
	}

	return &freshrpc.FreshAddResponse{
		FreshId: int64(fresh.ID),
	}, nil
}
